import { getGoodNum, AdvancePayment, requestPayment, chkOrder } from '../../services/pay'
import { getSetting, chooseAddress, openSetting, showModal, showToast } from '../../utils/util'
import regeneratorRuntime from '../../lib/runtime/runtime.js'
// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },


  // 商品选中


  // 设置购物车状态同时，重新计算
  setCart(cart) {



  },



  onShow: function () {
    // 1 获取缓存中的收货地址
    const address = wx.getStorageSync('address')
    // 获取缓存中的购物车数据
    let cart = wx.getStorageSync('cart') || []
    // every 数组 接收一个函数参数 每一个回调函数都返回true那么every方法返回值为true 
    // 只要有一个回调函数返回false那么不再循环执行 直接返回false

    // const allChecked =cart.length?cart.every(item=>{
    //   return item.checked
    // }):false
    // 过滤后的购物车数组
    cart = cart.filter(v => v.checked)
    // 总价格 总数量
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(item => {

      totalPrice += item.goods_price * item.num
      totalNum += item.num

    })

    this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    })

  },
  async handleOrderPay() {
    try {
      //1 判断缓存中有没有token
      const token = wx.getStorageSync('token')
      //2 判断
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }

      console.log("已经存在token")
      // 创建订单
      // 1.准备请求头参数
      // const header = { Authorization: token }
      // 2.请求体参数
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address
      let goods = [];
      const cart = this.data.cart
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = { order_price, consignee_addr, goods }
      // 4.准备发送请求 创建订单编号
      const { order_number } = await getGoodNum({ data: orderParams })
      // 5.发起预支付接口
      const { pay } = await AdvancePayment({ data: { order_number } })
      // 返回{order_number,pay:{nonceStr,package,paysign,signType,timeStamp}}
      //6.发起微信支付
      await requestPayment(pay)
      //7.查询订单状态
      const { res } = await chkOrder({ data: { order_number } })
      console.log(res)
      await showToast({title:"支付成功"})
      //8.手动删除缓存中已经支付的商品
      // 由于data中的cart是已经被筛选过的所以需要重新获取缓存中的数据
      
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(v=>!v.checked)
      wx.setStorageSync('cart', newCart)
      //9.支付成功后跳转到订单页面
      wx.navigateTo({
        url:'/pages/order/index'
      })
    } catch (e) { 
      await showToast({title:"支付失败"})
      console.log(e) }


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})